package com.ke.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Bochen
 */
@Component
public class JwtUtils {

    @Value("${jwt.security}")
    private String security;
    @Value("${jwt.issuer}")
    private String issuer;

    public String createToken(Map<String, String> map){

        long l = System.currentTimeMillis();
        l+=60*60*1000;
        Date date = new Date(l);
        //设置加密的方式
        Algorithm algorithm = Algorithm.HMAC256(security);
        //设置 头部
        Map<String, Object> headMap = new HashMap<>();
        headMap.put("alg","HS256");
        headMap.put("typ","JWT");
        //生成jwt
        return JWT.create().withHeader(headMap)
                .withSubject("用户认证")
                .withIssuer(issuer)
                //设置自定义内容用户名称
                .withClaim("username", map.get("username"))
                //设置自定义内容用户的id
                //目前只设置了用户名
                .withClaim("id",map.get("id"))
                .withIssuedAt(new Date())
                //设置失效时间
                .withExpiresAt(date)
                .sign(algorithm);
    }

    public Map<String, String> verifyToken(String token){
        //设置解密的方式
        Algorithm algorithm = Algorithm.HMAC256(security);
        //生成解密的对象
        JWTVerifier build = JWT.require(algorithm).withIssuer(issuer).build();
        //使用解密对象解析传入的token串
        try {
            DecodedJWT verify = build.verify(token);
            //从解密 的jwt中获取到需要的内容
            Map<String, String> map = new HashMap<>();
            map.put("username",verify.getClaim("username").asString());
            map.put("id",verify.getClaim("id").asString());
            return map;
        }catch (Exception e){
            return null;
        }
    }
}

